import { AsyncStorage } from "react-native";
import Config from "./common/config";

export const TOKEN_KEY = "__user_token__";

export const onLogin = (data) => {
  return AsyncStorage.setItem(TOKEN_KEY, JSON.stringify(data));
}

export const isAuthenticated = () => {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem(TOKEN_KEY)
      .then(res => {
        if (res !== null) {
          resolve(true);
        } else {
          resolve(false);
        }
      })
      .catch(err => reject(err));
  });
};

export const login = async (data) => {
  let options = {
    method: "post",
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  }
  let response = await fetch(Config.api.login, options);
  let responseJson = response.json();
  return responseJson;
}

export const logout = async () => {
  return AsyncStorage.removeItem(TOKEN_KEY);
}